package com.admin.education.models;

import com.admin.education.common.exceptions.BadRequestException;
import com.admin.education.dataTransferObject.votes.Request.VotesRequest;
import com.admin.education.repositories.Identifiable;
import com.alibaba.fastjson.annotation.JSONField;
import com.google.common.base.Verify;
import io.jsonwebtoken.lang.Assert;
import lombok.Data;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Entity
@Table(name = "votes")
@EntityListeners(AuditingEntityListener.class)
@Data
public class Votes  implements Serializable, Identifiable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name="title")
    private String title;
    @Column(name="content")
    private String content;
    @OneToMany(mappedBy = "votes")
    @JSONField(serialize = false)
    private List<VotesDetail> votesDetails;
    @OneToMany(mappedBy = "votes")
    @JSONField(serialize = false)
    private List<VotesResult> votesResults;
    @ManyToMany
    @JSONField(serialize = false)
    private List<Categorys> categorys;
    @Column(name="create_time")
    private Date createTime;
    public List<VotesResult> ballots(String openId, List<VotesRequest> votesRequests) throws BadRequestException {
        Verify.verify(null!=openId);

        if(this.votesResults.stream().anyMatch(p->p.getOpenId().equals(openId))){
            throw new BadRequestException("不能重复投票");
        }
        if(null!=this.votesDetails){
            List<VotesResult> votesResults = new ArrayList<>();
            for (VotesDetail votesDetail : this.votesDetails) {
                Optional<VotesRequest> optionalVotesRequest =  votesRequests.stream().filter(p->p.getId()==votesDetail.getId()).findFirst();
                if(optionalVotesRequest.isPresent()){
                    VotesResult votesResult = new VotesResult();
                    votesResult.setOpenId(openId);
                    votesResult.setVotes(this);
                    votesResult.setVotesDetail(votesDetail);

                    votesResults.add(votesResult);
                }
            }

            return votesResults;
        }
        return null;
    }
}
